<?php

/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/7/22
 * Time: 上午10:27
 */

namespace App\Http\Controllers;

use App\Models\Apart;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
    protected $domain;

    protected $cookie;

    public function __construct()
    {
        $this->domain = env('DOMAIN');
        $this->cookie = env('COOKIE_DOMAIN');
    }

    protected function sendJson(array $data, $status = 200, $message = 'OK')
    {
        echo json_encode([
            'body' => count($data) ? $data : new \stdClass(),
            'status' => $status,
            'message' => $message
        ]);exit;
    }

    protected function sendDataTable(array $data)
    {
        echo json_encode($data);exit;
    }

    protected function sendGet($callback)
    {
        try {
            $callback();
        } catch(\Exception $e) {
            $this->sendJson([], $e->getCode(), $e->getMessage());
        }
    }

    protected function sendPost($callback)
    {
        try {
            $callback();
        } catch(\Exception $e) {
            $this->sendJson([], $e->getCode(), $e->getMessage());

        }
    }

    protected function baseView(Request $request, $view, array $params)
    {
        $token = $request->get('_token');
        $role = $request->get('role');
        return view($view, array_merge($params, ['domain' => $this->domain, 'cookie' => $this->cookie, 'token' => $token, 'role' => $role]));
    }

    protected function searchApartIdsByName($search)
    {
        $aparts = Apart::where('name', 'like', "%{$search}%")->get();
        $ids = [];
        foreach ($aparts as $apart) {
            $ids[] = $apart->id;
        }
        if (count($ids) == 0) {
            $ids = [0];
        }
        return $ids;
    }

}
